package com.flyme.module.base.provider.handler;

import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.PayMessage;
import com.egzosn.pay.common.bean.PayOutMessage;
import com.egzosn.pay.common.exception.PayErrorException;
import com.flyme.common.core.model.ResultBody;
import com.flyme.module.base.client.entity.SysStudyconfig;
import com.flyme.module.base.client.entity.SysUsercertificate;
import com.flyme.module.base.client.entity.SysUserstudy;
import com.flyme.module.base.provider.service.SysBalanceService;
import com.flyme.module.base.provider.service.SysStudyconfigService;
import com.flyme.module.base.provider.service.SysUsercertificateService;
import com.flyme.module.base.provider.service.SysUserstudyService;
import com.flyme.module.order.client.entity.MyPayOrder;
import com.flyme.module.order.client.entity.Order;
import com.flyme.module.order.client.entity.OrderInfo;
import com.flyme.module.order.client.entity.PayBeforeHandler;
import com.flyme.module.order.client.enums.OrderStatusEnum;
import com.flyme.module.order.client.enums.PayTypeEnum;
import com.flyme.module.order.provider.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@Component("studycoursePayHandler")
@Slf4j
public class StudyCoursePayHandler  implements PayBeforeHandler {
    @Autowired
    private OrderService orderService;
    @Autowired
    private SysStudyconfigService sysStudyconfigService;
    @Autowired
    private SysUsercertificateService sysUsercertificateService;
    @Autowired
    private SysBalanceService balanceService;
    @Autowired
    private SysUserstudyService sysUserstudyService;

    /**
     * 创建订单
     */
    @Override
    public ResultBody addOrder(HttpServletRequest request, OrderInfo orderInfo) {
        log.error("==================================================继续教育订单创建进入");
        Long sysusercertId = orderInfo.getTargetId();

        SysUsercertificate sysUsercertificate= sysUsercertificateService.getById(sysusercertId);
        SysStudyconfig sysStudyconfig=sysStudyconfigService.getByStudyConfig(sysUsercertificate.getCertificateId());
        SysUserstudy userstudy=new SysUserstudy();
        userstudy.setUserCertificateId(sysusercertId);
        userstudy.setUserId(orderInfo.getUserId());
        userstudy.setStatus("0");
        sysUserstudyService.save(userstudy);
        orderInfo.setAmount(sysStudyconfig.getRegistrationFee());
        orderInfo.setBody("证书继续教育");
        return orderService.createOrder(orderInfo);
    }

    /**
     * 获取支付参数
     */
    @Override
    public MyPayOrder getPayOrder(HttpServletRequest request) {
        MyPayOrder order = new MyPayOrder();
        order.setMethedType("APP");
        order.setTest(false);
        return order;
    }

    /**
     * 支付回调验证验证
     */
    @SuppressWarnings("rawtypes")
    @Override
    public boolean intercept(PayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
        // 重复回调不进行处理
        String outTradeNo = payMessage.getOutTradeNo();
        Order order = orderService.findByNo(outTradeNo);
        if(!order.getOrderStatus().equals(OrderStatusEnum.unpaid)){//订单不为未支付，重复回调
            return false;
        }
        return true;
    }

    /**
     * 回调成功业务处理
     */
    @SuppressWarnings("rawtypes")
    @Override
    public PayOutMessage handle(PayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
        String payCode = String.valueOf(payService.getPayConfigStorage().getPayType());
        Map<String, Object> message = payMessage.getPayMessage();
        //交易状态
        String trade_status = (String) message.get("trade_status");
        //上下文对象中获取账单
        //AmtApply amtApply = (AmtApply)context.get("amtApply");
        //日志存储
        //amtPaylogService.createAmtPaylogByCallBack(amtApply,  message.toString());
        if("aliPay".equals(payCode)){//支付宝
            //交易完成
            if ("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)) {//支付成功或支付完成
                //BigDecimal payAmount = new BigDecimal((String) message.get("total_fee"));
                String outTradeNo = payMessage.getOutTradeNo();
                Order order = orderService.findByNo(outTradeNo);
                order.setPayType(PayTypeEnum.Alipay);
                balanceService.pay_back(order);
                return payService.getPayOutMessage("success", "成功");
            }/* else if ("WAIT_BUYER_PAY".equals(trade_status) || "TRADE_CLOSED".equals(trade_status)) {//支付等待或支付关闭

            }*/
        }
        if("wxPay".equals(payCode)){//微信支付
            if ("SUCCESS".equals(payMessage.getPayMessage().get("result_code"))){
                /////这里进行成功的处理
                String outTradeNo = payMessage.getOutTradeNo();
                Order order = orderService.findByNo(outTradeNo);
                order.setPayType(PayTypeEnum.WxPay);
                balanceService.pay_back(order);
                return  payService.getPayOutMessage("SUCCESS", "OK");
            }else{
                return payService.getPayOutMessage("FAIL", "失败");
            }
        }

        return payService.getPayOutMessage("fail", "失败");
    }
}
